#include "account.h"
#include "QVariant"
#include "QDebug"
#include "QMessageBox"

account::account()
{}

account::account(int type, QString name, QString passwd, QString telnumber)
    :userType(type)
    ,username(name)
    ,password(passwd)
    ,telNumber(telnumber)
{}

void account::insertToDB()
{
    QSqlDatabase sqlite = QSqlDatabase::database("MY");
    QSqlQuery query(sqlite);
    //先查询数据是否存在，若存在则提示
    //若不存在，通过type判断来插入哪一个表
    if(userType == 0)//普通用户
    {
        query.prepare("SELECT * FROM CUSTOMER WHERE telNumber = ? ");
        query.addBindValue(this->telNumber);
        if(!query.exec())
        {
            return;
        }

        if(query.next())
        {
            QMessageBox box;
            box.setWindowTitle("warning");
            box.setText("该手机号码已被注册");
            box.setIcon(QMessageBox::Warning);
            box.exec();
            return;
        }
        else
        {
            query.prepare("INSERT INTO CUSTOMER(username,password,telNumber)\
                   VALUES(?,?,?)");
        }

    }
    else if(userType == 1)//营业员
    {
        query.prepare("SELECT * FROM CLERK WHERE telNumber = ? ");
        query.addBindValue(this->telNumber);
        if(!query.exec())
        {
            return;
        }

        if(query.next())
        {
            QMessageBox box;
            box.setWindowTitle("warning");
            box.setText("该手机号码已被注册");
            box.setIcon(QMessageBox::Warning);
            box.exec();
            return;
        }
        else
        {
            query.prepare("INSERT INTO CLERK(username,password,telNumber)\
                   VALUES(?,?,?)");
        }
    }
    else//经理
    {
        query.prepare("SELECT * FROM MANAGER WHERE telNumber = ? ");
        query.addBindValue(this->telNumber);
        if(!query.exec())
        {
            return;
        }

        if(query.next())
        {
            QMessageBox box;
            box.setWindowTitle("warning");
            box.setText("该手机号码已被注册");
            box.setIcon(QMessageBox::Warning);
            box.exec();
            return;
        }
        else
        {
            query.prepare("INSERT INTO MANAGER(username,password,telNumber)\
                   VALUES(?,?,?)");
        }
    }
    query.addBindValue(username);
    query.addBindValue(password);
    query.addBindValue(telNumber);
    if(query.exec())
    {
        QMessageBox box;
        box.setWindowTitle("completed");
        box.setText("注册成功");
        box.setIcon(QMessageBox::Information);
        box.exec();
    }
    return;
}



